/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sigmatrix.h5.dao.WarehouseStockDao;
import com.sigmatrix.h5.dao.WarehouseStockDetailsDao;
import com.sigmatrix.h5.dto.ProductData;
import com.sigmatrix.h5.entity.WarehouseStock;
import com.sigmatrix.h5.entity.WarehouseStockDetails;
import com.sigmatrix.h5.exception.DaoException;
import com.sigmatrix.h5.exception.ServiceException;
import com.sigmatrix.h5.service.ProductService;
import com.sigmatrix.h5.service.WarehouseStockDetailsService;
import com.sigmatrix.h5.service.common.impl.BaseServiceImpl;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.Utils;

/**
 *@ClassName: WarehouseStockDetailsServiceImpl
 *@Description: TODO()
 *@author youjun
 *@date 2017年8月27日 下午6:48:23
 */
@Service(value="warehouseStockDetailsService")
public class WarehouseStockDetailsServiceImpl extends BaseServiceImpl<WarehouseStockDetails> implements WarehouseStockDetailsService {

	/**logger record*/
	private static final Logger LOGGER = LoggerFactory.getLogger(WarehouseStockDetailsServiceImpl.class);
	
	/**库存详情数据库操作接口*/
	@Autowired
	private transient WarehouseStockDetailsDao warehouseStockDetailsDao;
	
	/**库存数据库操作接口*/
	@Autowired
	private transient WarehouseStockDao warehouseStockDao;
	
	@Autowired
	private transient ProductService productService;
	
	/**(non-Javadoc)
	 *@Title: batchSave
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.WarehouseStockDetailsService#batchSave(int, int, java.lang.String, java.util.List, java.lang.String)
	 *@author youjun
	 *@date 2017年8月27日 下午6:53:00
	 */
	@Override
	public int batchSave(final int warehouseId, final int productId, final String batchCode, final List<String> batchBoxList, final String enterpriseCode) throws ServiceException {

		if(!CollectionUtils.isEmpty(batchBoxList)) {
			final WarehouseStock warehouseStockCondition = new WarehouseStock();
			warehouseStockCondition.setWarehouseId(warehouseId);
			warehouseStockCondition.setProductId(productId);
			try{
				// 根据仓库ID、产品ID、批次code查询库存记录
				final List<WarehouseStock> stockList = warehouseStockDao.findListByCondition(warehouseStockCondition, enterpriseCode);
				if(CollectionUtils.isEmpty(stockList)) {
					final StringBuilder errorMsg = new StringBuilder();
					errorMsg.append("根据库存产品批次无法查找到库存记录");
					LOGGER.error("根据库存ID:{},产品ID:{},批次:{},无法查找到库存记录", warehouseId, productId, batchCode);
					throw new ServiceException("根据库存产品批次无法查找到库存记录");
				}
				final Long stockId = stockList.get(0).getId();
				final List<WarehouseStockDetails> warehouseStockDetailsList = new ArrayList<WarehouseStockDetails>();
				WarehouseStockDetails item = null;
				for(final String box:batchBoxList) {
					item = new WarehouseStockDetails();
					item.setCode(box);
					item.setCreateTime(new Date());
					item.setStatus(Cons.WH_STOCK_DETAILS_STATUS_IN_STORAGE);
					item.setStockId(stockId);
					warehouseStockDetailsList.add(item);
				}
				LOGGER.info("批量入库存详情：仓库ID:{},产品ID:{},批次号:{},对应的库存ID为:{}", warehouseId, productId, batchCode, stockId);
				LOGGER.info("入库存ID为:{}的详情列表为:{}", stockId, JSONObject.toJSONString(warehouseStockDetailsList));
				return warehouseStockDetailsDao.batchSave(warehouseStockDetailsList, enterpriseCode);
			}catch(DaoException e) {
				throw new ServiceException(e);
			}
		}
		return 0;
	}

	/**(non-Javadoc)
	 *@Title: batchUpdateBoxsStatus
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.WarehouseStockDetailsService#batchUpdateBoxsStatus(int, int, java.lang.String, java.util.List, java.lang.String)
	 *@author youjun
	 *@date 2017年8月28日 下午4:59:42
	 */
	@Override
	public int batchUpdateBoxsStatus(final int warehouseId, final int productId, final List<String> boxList,
			final List<String> singleList,final short status,
			final String enterpriseCode) throws ServiceException {

		if(StringUtils.isBlank(enterpriseCode)) {
			throw new ServiceException("企业code不能为空");
		}
		final ProductData product = productService.findById(productId, enterpriseCode);
		if(!CollectionUtils.isEmpty(boxList)) {
			final WarehouseStock warehouseStockCondition = new WarehouseStock();
			warehouseStockCondition.setWarehouseId(warehouseId);
			warehouseStockCondition.setProductId(productId);
			warehouseStockCondition.setLevel(product.getProductUnit().intValue());
			try{
				// 根据仓库ID、产品ID、批次code查询库存记录
				final List<WarehouseStock> stockList = warehouseStockDao.findListByCondition(warehouseStockCondition, enterpriseCode);
				if(CollectionUtils.isEmpty(stockList)) {
					final StringBuilder errorMsg = new StringBuilder();
					errorMsg.append("根据库存产品批次无法查找到库存记录");
					LOGGER.error("根据库存ID:{},产品ID:{},无法查找到库存记录", warehouseId, productId);
					throw new ServiceException("根据库存产品批次无法查找到库存记录");
				}
				final Long stockId = stockList.get(0).getId();
				LOGGER.info("批量出库更新出库码详情：仓库ID:{},产品ID:{},批次号:{},对应的库存ID为:{}", warehouseId, productId, stockId);
				LOGGER.info("出库时拿取库存ID为:{}，将要操作的包装码列表为:{}", stockId, JSONObject.toJSONString(boxList));
				
				//待更新处理的条数  sqlServer 批量更新大于2000条报错(后期进行优化处理)
				int num = 0;
				List<String> countList = new ArrayList<>();
				for (int i = 0; i < boxList.size(); i++) {
					num ++;
					countList.add(boxList.get(i));
					if (num % 1000 == 0) {
						//批量添加
						warehouseStockDetailsDao.batchUpdateStatus(stockId, countList, status, enterpriseCode);
						//清空
						countList.clear();
					}
				}
				if (Utils.isNotEmpty(countList)) {
					//批量添加
					warehouseStockDetailsDao.batchUpdateStatus(stockId, countList, status, enterpriseCode);
					//清空
					countList.clear();
				}
				
				
				
			}catch(DaoException e) {
				throw new ServiceException(e);
			}
		}
		if(!CollectionUtils.isEmpty(singleList)) {
			final WarehouseStock warehouseStockCondition = new WarehouseStock();
			warehouseStockCondition.setWarehouseId(warehouseId);
			warehouseStockCondition.setProductId(productId);
			warehouseStockCondition.setLevel(1);
			try{
				// 根据仓库ID、产品ID、批次code查询库存记录
				final List<WarehouseStock> stockList = warehouseStockDao.findListByCondition(warehouseStockCondition, enterpriseCode);
				if(CollectionUtils.isEmpty(stockList)) {
					final StringBuilder errorMsg = new StringBuilder();
					errorMsg.append("根据库存产品批次无法查找到库存记录");
					LOGGER.error("根据库存ID:{},产品ID:{},包装级别:{},无法查找到库存记录", warehouseId, productId, 1);
					throw new ServiceException("根据库存产品批次无法查找到库存记录");
				}
				final Long stockId = stockList.get(0).getId();
				LOGGER.info("批量出库更新出库码详情：仓库ID:{},产品ID:{},批次号:{},对应的库存ID为:{}", warehouseId, productId, stockId);
				LOGGER.info("出库时拿取库存ID为:{}，将要操作的单品码列表为:{}", stockId, JSONObject.toJSONString(singleList));	
				//待更新处理的条数  sqlServer 批量更新大于2000条报错(后期进行优化处理)
				int num = 0;
				List<String> countList = new ArrayList<>();
				for (int i = 0; i < boxList.size(); i++) {
					num ++;
					countList.add(boxList.get(i));
					if (num % 1000 == 0) {
						//批量添加
						warehouseStockDetailsDao.batchUpdateStatus(stockId, countList, status, enterpriseCode);
						//清空
						countList.clear();
					}
				}
				if (Utils.isNotEmpty(countList)) {
					//批量添加
					warehouseStockDetailsDao.batchUpdateStatus(stockId, countList, status, enterpriseCode);
					//清空
					countList.clear();
				}
				
			
			}catch(DaoException e) {
				throw new ServiceException(e);
			}
		}
		return 0;
	}


	/**
	 * (non-Javadoc)
	 *@Title: countByConditionOut
	 *@Description: 
	 *@see com.sigmatrix.h5.service.WarehouseStockDetailsService#countByConditionOut(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.String, int)
	 *@author gaomingkai
	 *@date 2017年10月31日 下午11:20:37
	 */
	@Override
	public Integer countByConditionOut(final String eseCode, final Integer warehosueId, final Integer productId, final String code, final int status,final boolean isflag) {
		// TODO Auto-generated method stub
		return warehouseStockDetailsDao.countByConditionOut(eseCode, warehosueId, productId, code, status,isflag);
	}

	/**
	 * (non-Javadoc)
	 *@Title: findByConditionOut
	 *@Description: 
	 *@see com.sigmatrix.h5.service.WarehouseStockDetailsService#findByConditionOut(java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.String, int)
	 *@author gaomingkai
	 *@date 2017年11月24日 下午5:41:20
	 */
	@Override
	public List<WarehouseStockDetails> findByConditionOut(String eseCode, Integer warehosueId, Integer productId,
			String code, int stauts) {
		// TODO Auto-generated method stub
		return warehouseStockDetailsDao.findByConditionOut(eseCode, warehosueId, productId, code, stauts);
	}


	
}
